package com.lanhai.utils;

import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

public class RegionUtil {
  private static double EARTH_RADIUS = 6378137;
  //private static double EARTH_SEA = 1.852;海里

  private static double rad(double d) {
      return d * Math.PI / 180.0;
  }

  /**
   * 判断是否在多边形区域内
   *
   * @param pointLon 要判断的点的横坐标 经度
   * @param pointLat 要判断的点的纵坐标 维度
   * @param lon      区域各顶点的横坐标数组
   * @param lat      区域各顶点的纵坐标数组
   * @return
   */
  public static boolean isInPolygon(double pointLon, double pointLat, Double[] lon,
                                    Double[] lat) {
      // 将要判断的横纵坐标组成一个点
      Point2D.Double point = new Point2D.Double(pointLon, pointLat);
      // 将区域各顶点的横纵坐标放到一个点集合里面
      List<Point2D.Double> pointList = new ArrayList<Point2D.Double>();
      double polygonPoint_x = 0.0, polygonPoint_y = 0.0;
      StringBuffer sb = new StringBuffer();
      for (int i = 0; i < lon.length; i++) {
          polygonPoint_x = lon[i];
          polygonPoint_y = lat[i];
          Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x, polygonPoint_y);
          pointList.add(polygonPoint);
          sb.append("p" + i + ":[" + lon[i] + "," + lat[i] + "],");
      }
      System.out.println(sb.toString());
      return check(point, pointList);
  }

  /**
   * @param point   要判断的点的横纵坐标
   * @param polygon 组成的顶点坐标集合
   * @return
   */
  private static boolean check(Point2D.Double point, List<Point2D.Double> polygon) {
      java.awt.geom.GeneralPath peneralPath = new java.awt.geom.GeneralPath();

      Point2D.Double first = polygon.get(0);
      // 通过移动到指定坐标（以双精度指定），将一个点添加到路径中
      peneralPath.moveTo(first.x, first.y);
      polygon.remove(0);
      for (Point2D.Double d : polygon) {
          // 通过绘制一条从当前坐标到新指定坐标（以双精度指定）的直线，将一个点添加到路径中。
          peneralPath.lineTo(d.x, d.y);
      }
      // 将几何多边形封闭
      peneralPath.lineTo(first.x, first.y);
      peneralPath.closePath();
      // 测试指定的 Point2D 是否在 Shape 的边界内。
      return peneralPath.contains(point);
  }

  /**
   * 通过经纬度获取距离(单位：米)
   *
   * @param lat1 纬度1
   * @param lng1 经度1
   * @param lat2 纬度2
   * @param lng2 经度2
   * @return 距离
   */
  public static double getDistance(double lat1, double lng1, double lat2,
                                   double lng2) {
      double radLat1 = rad(lat1);
      double radLat2 = rad(lat2);
      double a = radLat1 - radLat2;
      double b = rad(lng1) - rad(lng2);
      double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
      s = s * EARTH_RADIUS;
      s = Math.round(s * 10000d) / 10000d;
      //double len=s/EARTH_SEA;
      //s = s / 1000;
      return s;
  }

  /**
   * @param lat1   纬度
   * @param lat2   纬度
   * @param lng1   经度
   * @param lng2   经度
   * @param radius 判断一个点是否在圆形区域内,比较坐标点与圆心的距离是否小于半径
   */
  public static boolean isInCircle(double lng1, double lat1, double lng2, double lat2, double radius) {
      double distance = getDistance(lat1, lng1, lat2, lng2);
      if (distance > radius) {
          return false;
      } else {
          //System.err.println("经度："+lng1+"维度："+lat1+"经度："+lng2+"维度："+lat2+"距离:"+distance);
          return true;
      }
  }
  
	/**
	 * 计算两个点的直线距离
	 * @return
	 */
	public static double distance(double x1, double y1, double x2, double y2){
		double x12 = (x2-x1);
		double y12 = (y2-y1);
		double p12 = x12*x12+y12*y12;
		return Math.sqrt(p12);//开平方根
	}
	/**
	 * 根据多个顶点的座标获得一个多边形
	 * @param lon
	 * @param lat
	 * @return
	 */
	public static GeneralPath getCtrlShape(Double[] lon, Double[] lat){
		GeneralPath peneralPath = new GeneralPath();
		peneralPath.moveTo(lon[0], lat[0]);
		for (int i = 1; i < lon.length; i++) {
			peneralPath.lineTo(lon[i], lat[i]);
		}
		// 将几何多边形封闭
		peneralPath.lineTo(lon[0], lat[0]);
		peneralPath.closePath();
		return peneralPath;
	}
	/**
	 * 根据偏移座标获取移动角度
	 * @param angx
	 * @param angy
	 * @return
	 */
	public static double getAngle(double angx, double angy){
		double at2 = Math.atan2(angy,angx);
		return at2*180/Math.PI;
	}
	
    //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
	public static int getDirection(double startx, double starty, double endx, double endy) {
        double angx = endx - startx;
        double angy = endy - starty;
        int result = 0;
 
        //如果滑动距离太短
        if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
            return result;
        }
 
        double angle = getAngle(angx, angy);
        if (angle >= -135 && angle <= -45) {
            result = 1;
        } else if (angle > 45 && angle < 135) {
            result = 2;
        } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;
        }
        return result;
    }	
	
	public static void main(String[] args){
		Double[] lonArr = {50.0, 50.0, 100.0, 100.0};
		Double[] latArr = {50.0, 100.0, 100.0, 50.0};
		getCtrlShape(lonArr, latArr);
		System.out.println(isInPolygon(101.0, 101.0, lonArr, latArr));
		double angy = 100.0;
		double angx = 100.0;
		double at2 = Math.atan2(angy,angx);
		System.out.println("atan2:" + at2*180/Math.PI);
	}
	
}
